<template>
  <div>
      <el-dialog   :modelValue="dialogVisible"  title="搜索点"  width="50%"
                  :close-on-click-modal="false" :close-on-press-escape="false"
                  :show-close="false" > 
                  <div style="display: flex; align-items: center; margin-bottom: 15px;">
            <span style="margin-right: 10px;">项目选择：</span>
            <el-select v-model="currentPrefix" placeholder="请选择项目" style="flex: 1" @change="handleProjectChange">
              <el-option
                v-for="item in projects"
                :key="item.prefix"
                :label="item.descr"
                :value="item.prefix">
              </el-option>
            </el-select>
<el-button @click="init" icon="el-icon-refresh">刷新项目</el-button>
            <el-button @click="handleGetItemYc" >从实时库取遥测</el-button>
            <el-button @click="handleGetItemYx" >从实时库取遥信</el-button>
            <el-button @click="handleGetItemYcFromMysql" >从关系库取遥测</el-button>
            <el-button @click="handleGetItemYxFromMysql" >从关系库取遥信</el-button>               

          </div>

        <div style="display: flex;" >
          <el-text style="width: 100px;" >关键字：</el-text>
          <el-input v-model="strkey" @keyup.enter="handleSearchItem"></el-input>
          <el-button @click="handleSearchItem" >搜索</el-button>
        </div>
        <el-text  style="display: inline-block; text-align: left;" >结果：</el-text>
        <el-table v-loading="isLoading"  :data="datitemtable"
            style="height: 30vh; border: 1px solid black;" 
            element-loading-text="正在加载数据..."
            :header-cell-style="{ backgroundColor: '#34e0e6', color: '#000000' }"

            @current-change="handleCurrentChange"
            :row-style="rowStyle"
        >
          <el-table-column prop="key" label="地址" width="150" />
          <el-table-column prop="descr" label="描述" width="500" />
        </el-table>
        <span>数据条数：{{ rowcount }}</span>

        <template #footer>
          <div style="display: flex; flex-direction: row-reverse; ">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleOk"  style="margin: 0 10px 0 10px;" >确定</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script>

import {ElMessage} from "element-plus";
import request from "@/utils/drawutils/request";
import { mapState } from 'vuex'

export default {
  name: "DlgSearchKey",
  props:{ dialogVisible: Boolean },
  components:{},
  emits:[ "resSearchItem" ],

  mounted() {
    this.init()
  },
  computed:{
    rowcount(){
      return this.datitemtable.length
    },
    ...mapState([
        'prefix',
    ]),    

  },
  data(){
    return{
      datitemFromDb : [],  //从库中读出的点
      datitemtable : [],  //要显示的点
      strkey: "",
      isLoading: false,
      currentRow: null,

      projects: [],
      currentPrefix: '',
      currentDbid: -1,
    }
  },
  watch: {

  },
  methods:{
    async init(  ){
      let res = await request.post( "/drwproject/getallprojects" )
      if( res.code === '1' ){
          this.projects = res.data
          if(this.projects.length > 0) {
            this.currentPrefix = this.projects[0].prefix
            this.currentDbid = this.projects[0].dbid
          }
      }
      // console.log( "projects: ", this.projects )
    },  

    handleGetItemYc(  ){
        // 创建 XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();

        // 准备要发送的数据
        var params = 'dbid=' + this.currentDbid + "&prefix=" + this.currentPrefix;

        // 配置请求
        xhr.open('POST', window.location.origin + '/drawapi/redisdb/getyc', true);

        // 设置请求头
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        // 定义请求成功时的回调函数
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                
                
                // 请求成功，处理响应
                // console.log('请求成功:', xhr.responseText);
                
                // 如果服务器返回的是JSON格式的数据
                try {
                    var res = JSON.parse(xhr.responseText);
                    this.datitemFromDb =  res.data
                    this.datitemtable =  res.data
                    this.isLoading = false
                    console.log( this.isLoading )
                    console.log('解析后的响应数据:', res);
                } catch (e) {
                    console.error('解析响应数据失败:', e);
                }
                
            } else {
                // 处理错误情况
                console.error('请求失败: 状态码 ' + xhr.status + ', 响应文本: ' + xhr.responseText);
            }
        }.bind(this);

        // 定义请求出错时的回调函数
        xhr.onerror = function () {
            console.error('网络错误');
            this.isLoading = false
        }.bind(this);

        // 发送请求
        xhr.send(params);
        this.isLoading = true
    },

        //取数据平面的点信息
    handleGetItemYc1(  ){
      let url = "/redisdb/getyc?dbid="+this.currentDbid
      request.post( url ).then( res=>{
        this.datitemFromDb =  res.data
        this.datitemtable =  res.data
        console.log(res)
      })
    },

    handleGetItemYx(  ){
        // 创建 XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();

        // 准备要发送的数据
        var params = 'dbid=' + this.currentDbid + "&prefix=" + this.currentPrefix;

        // 配置请求
        
        xhr.open('POST', window.location.origin + '/drawapi/redisdb/getyx', true);

        // 设置请求头
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        // 定义请求成功时的回调函数
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                
                
                // 请求成功，处理响应
                // console.log('请求成功:', xhr.responseText);
                
                // 如果服务器返回的是JSON格式的数据
                try {
                    var res = JSON.parse(xhr.responseText);
                    this.datitemFromDb =  res.data
                    this.datitemtable =  res.data
                    this.isLoading = false
                    console.log( this.isLoading )
                    console.log('解析后的响应数据:', res);
                } catch (e) {
                    console.error('解析响应数据失败:', e);
                }
                
            } else {
                // 处理错误情况
                console.error('请求失败: 状态码 ' + xhr.status + ', 响应文本: ' + xhr.responseText);
            }
        }.bind(this);

        // 定义请求出错时的回调函数
        xhr.onerror = function () {
            console.error('网络错误');
            this.isLoading = false
        }.bind(this);

        // 发送请求
        xhr.send(params);
        this.isLoading = true      
    },    

    async handleGetItemYcFromMysql(  ){
      let res = await request.post( "/hg3000/getdatayc?projectPrefix="+this.currentPrefix )
      if( res.code === '1' ){
          res.data.forEach( item=>{
            item.key =  this.currentPrefix + "-yc" + item.stationid + "-"+ item.id
          })
          this.datitemFromDb = res.data
          this.datitemtable = res.data
      }
      else{
        this.datitemFromDb = []
        this.datitemtable = []
        ElMessage.error( res.msg )
      }        
      console.log( "get datayc: ", "" )   
    },

    async handleGetItemYxFromMysql(  ){
      let res = await request.post( "/hg3000/getdatayx?projectPrefix="+this.currentPrefix )
      if( res.code === '1' ){
          res.data.forEach( item=>{
            item.key =  this.currentPrefix + "-yx" + item.stationid + "-"+ item.id
          })
          this.datitemFromDb = res.data
          this.datitemtable = res.data
      }
      else{
        this.datitemFromDb = []
        this.datitemtable = []
        ElMessage.error( res.msg )
      }        
      console.log( "get datayx: ", "" )
      
    },

    //从点信息搜索相应的点
    handleSearchItem(  ){
      this.datitemtable = this.datitemFromDb.filter(item => item.descr.includes( this.strkey ) || item.key.includes( this.strkey ));
    },

    handleOk(  ){
      this.currentRow.dbid = this.currentDbid
      this.$emit( "resSearchItem", 1, this.currentRow )
    },

    handleCancel(){
      this.$emit( "resSearchItem", 0 )
    },

    handleCurrentChange(val) {
      this.currentRow = val; // 监听当前行变化
      //console.log( "currentrow:", this.currentRow )
    },

    rowStyle(row) {
      // 如果是当前行，返回指定样式
      if (row.row === this.currentRow) {
        return { backgroundColor: '#5adb81' }; // 自定义底色
      }
    },

    handleProjectChange(val) { 
      if ( val ) {
        const result = this.projects.filter(project => project.prefix === val);
        this.currentDbid = result[0].dbid; // 假设每个项目只有一个dbid
        // console.log( "current change dbid: ", this.currentDbid )
      } 
    }
  },  // end of methods

}

</script>

<style  lang="less" scoped >

</style>